package cc.ppay.sso.core.login;

import cc.ppay.sso.common.constant.SsoConstant;
import cc.ppay.sso.common.model.SsoUser;
import cc.ppay.sso.core.store.SsoLoginStore;
import cc.ppay.sso.core.store.SsoSessionIdHelper;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录登出操作token
 *
 * @author Ade.Xiao 2021/1/29 17:24
 */
@Component
public class SsoTokenLoginHelper {
    @Autowired
    private SsoLoginStore ssoLoginStore;
    @Autowired
    private SsoSessionIdHelper ssoSessionIdHelper;

    /**
     * client login
     *
     * @param sessionId
     * @param ssoUser
     */
    public void login(String sessionId, SsoUser ssoUser) {

        String storeKey = ssoSessionIdHelper.parseStoreKey(SsoConstant.AUTH_TYPE_APP, sessionId);
        if (storeKey == null) {
            throw new RuntimeException("parseStoreKey Fail, sessionId:" + sessionId);
        }

        ssoLoginStore.put(storeKey, ssoUser);
    }

    /**
     * client logout
     *
     * @param sessionId
     */
    public void logout(String sessionId) {

        String storeKey = ssoSessionIdHelper.parseStoreKey(SsoConstant.AUTH_TYPE_APP, sessionId);
        if (storeKey == null) {
            return;
        }

        ssoLoginStore.remove(storeKey);
    }

    /**
     * client logout
     *
     * @param request
     */
    public void logout(HttpServletRequest request) {
        String headerSessionId = request.getHeader(SsoConstant.SSO_SESSIONID);
        logout(headerSessionId);
    }


    /**
     * login check
     *
     * @param sessionId
     * @return
     */
    public SsoUser loginCheck(String type, String sessionId) {
        if (StrUtil.isBlank(type) || StrUtil.isBlank(sessionId)) {
            return null;
        }

        String storeKey = ssoSessionIdHelper.parseStoreKey(type, sessionId);
        if (storeKey == null) {
            return null;
        }

        SsoUser ssoUser = ssoLoginStore.get(storeKey);
        if (ssoUser != null) {
            String version = ssoSessionIdHelper.parseVersion(sessionId);
            if (ssoUser.getVersion().equals(version)) {

                // After the expiration time has passed half, Auto refresh
                if ((System.currentTimeMillis() - ssoUser.getExpireFreshTime()) > ssoUser.getExpireMinute() / 2) {
                    ssoUser.setExpireFreshTime(System.currentTimeMillis());
                    ssoLoginStore.put(storeKey, ssoUser);
                }

                return ssoUser;
            }
        }
        return null;
    }


    /**
     * login check
     *
     * @param request
     * @return
     */
    public SsoUser loginCheck(HttpServletRequest request) {
        String headerSessionId = request.getHeader(SsoConstant.SSO_SESSIONID);
        return loginCheck(SsoConstant.AUTH_TYPE_APP, headerSessionId);
    }
}
